<template>
  <vxe-modal
    v-model="dialogFormVisible"
    :title="title"
    show-footer
    transfer
    fullscreen
    destroy-on-close
    :loading="listLoading"
    @close="close"
  >
    <template #default>
      <vxe-form
        ref="formRef"
        :data="form"
        :rules="rules"
        title-align="right"
        title-width="230"
      >
        <vxe-form-item title="所属部门" field="deptId" span="24">
          <template #default>
            <el-tree-select
              ref="orgRef"
              v-model="form.deptId"
              :data="deptTree"
              node-key="id"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children',
              }"
              :default-expanded-keys="[form.deptId]"
              :render-after-expand="false"
              :current-node-key="form.deptId"
              check-strictly
              highlight-current
              style="width: 320px"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item title="账号" field="username" span="12">
          <template #default>
            <el-input v-model="form.username" style="width: 160px" />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="登录密码"
          field="pwd"
          span="12"
          :title-prefix="{
            message: '密码长度为 12-16 位,必须包括大小写特殊字符',
            icon: 'vxe-icon-question-circle-fill',
          }"
        >
          <template #default>
            <el-input
              v-model="form.pwd"
              placeholder="请输入密码"
              show-password
              style="width: 220px"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item title="用户昵称" field="nickname" span="12">
          <template #default>
            <el-input v-model="form.nickname" style="width: 160px" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="岗位" field="posts" span="12">
          <template #default>
            <el-select
              v-model="form.postIds"
              class="filter-item"
              placeholder="请选择"
              style="width: 320px"
              multiple
              collapse-tags
              clearable
            >
              <el-option
                v-for="item in posts"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="员工号" field="employeeId" span="12">
          <template #default>
            <el-input v-model="form.employeeId" style="width: 230px" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="身份证号" field="idCard" span="12">
          <template #default>
            <el-input v-model="form.idCard" style="width: 230px" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="即时通帐号" field="im" span="12">
          <template #default>
            <el-input v-model="form.im" style="width: 160px" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="性别" field="sex" span="12">
          <template #default>
            <el-select
              v-model="form.sex"
              class="filter-item"
              placeholder="请选择"
              style="width: 120px"
            >
              <el-option
                v-for="item in sexList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="手机号码" field="mobile" span="12">
          <template #default>
            <el-input v-model="form.mobile" style="width: 160px" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="邮箱" field="email" span="12">
          <template #default>
            <el-input v-model="form.email" style="width: 230px" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="状态" field="status" span="24">
          <template #default>
            <el-select
              v-model="form.status"
              class="filter-item"
              placeholder="请选择"
              style="width: 120px"
            >
              <el-option
                v-for="item in statusList"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item span="24">
          <template #default>
            <div style="position: absolute; right: 4px; z-index: 100000">
              <el-button type="primary" @click="addUserRole">
                <i class="iconfont-fw icon-wpkj-add-select" />
                {{ translate('增加角色') }}
              </el-button>
              <el-button type="danger" plain @click="delUserRole">
                <i class="iconfont-fw icon-wpkj-eraser" />
                {{ translate('删除角色') }}
              </el-button>
            </div>
            <el-tabs model-value="role" class="demo-tabs">
              <el-tab-pane :label="translate('用户角色')" name="role">
                <vxe-grid
                  ref="roleGrid"
                  border
                  stripe
                  resizable
                  auto-resize
                  keep-source
                  highlight-current-row
                  align="center"
                  :columns="roleTableColumn"
                  :row-config="{
                    keyField: 'id',
                    useKey: 'id',
                  }"
                  :checkbox-config="{
                    highlight: true,
                    reserve: true,
                  }"
                  :edit-config="{
                    trigger: 'click',
                    mode: 'cell',
                    showStatus: true,
                    icon: 'fa fa-pencil',
                  }"
                  :column-config="{ useKey: 'id' }"
                  :edit-rules="rulesRoleTable"
                  height="450"
                >
                  <template #updateSelectRole="{ row }">
                    <el-select
                      v-model="row.dataScope"
                      class="filter-item"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in dataScope"
                        :key="item.value"
                        :disabled="item.value < row.qdataScope"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                  <template #selectRoleDataPermission="{ row }">
                    {{ selectRoleDataPermission(row) }}
                  </template>
                  <template #selectDept="{ row }">
                    <el-tree-select
                      ref="orgRef"
                      v-model="row.dataScopeDeptIds"
                      :data="deptTree"
                      node-key="id"
                      :props="{
                        value: 'id',
                        label: 'name',
                        children: 'children',
                      }"
                      :disabled="row.dataScope !== 2"
                      :default-expanded-keys="[row.dataScopeDeptIds]"
                      :render-after-expand="false"
                      check-strictly
                      multiple
                      show-checkbox
                      highlight-current
                    />
                  </template>
                  <template #deptName="{ row }">
                    {{ selectDeptName(row) }}
                  </template>
                </vxe-grid>
              </el-tab-pane>
            </el-tabs>
          </template>
        </vxe-form-item>
      </vxe-form>
    </template>
    <template #footer>
      <el-button type="primary" :loading="subLoading" @click="save">
        <i class="icon-wpkj-save"></i>
        {{ translate('确定') }}
      </el-button>
      <el-button type="danger" plain @click="close()">
        {{ translate('取消') }}
      </el-button>
    </template>
  </vxe-modal>
  <RoleList ref="roleListRef" @fetch-role-data="fetchData" />
</template>

<script>
  import { checkPasswordRule } from '@/utils/checkPassword'
  import {
    getOpt,
    getUserById,
    saveOrUpdateUser,
  } from '@/api/system/user/index'
  import { translate } from '@/i18n'

  export default defineComponent({
    name: 'UserEdit',
    components: {
      RoleList: defineAsyncComponent(() => import('./roleList')),
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const $XEUtils = inject('$XEUtils')
      const $baseLodash = inject('$baseLodash')

      const state = reactive({
        roleListRef: null,
        userImportForm: null,
        orgRef: null,
        formRef: null,
        roleGrid: null,
        form: {
          id: undefined, // 主键ID
          username: undefined, // 账号
          pwd: undefined, // 登录密码
          nickname: undefined, // 昵称
          sex: undefined, // 性别 0:男 1:女
          mobile: undefined, // 手机号码
          email: undefined, // 邮箱
          avatar: undefined, // 头像
          status: undefined, // 状态
          deptId: '', // 单位代码
          postIds: [], //岗位
          employeeId: '', //员工号
          userRoleDOList: [], //用户角色列表
        },
        roleQueryForm: { name: undefined },
        rules: {
          deptId: [
            { required: true, trigger: 'blur', message: '请输入处室/部门' },
          ],
          username: [
            { required: true, trigger: 'blur', message: '请输入用户名' },
          ],
          pwd: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入密码',
            },
            {
              validator({ itemValue, data }) {
                // 自定义校验
                const res = checkPasswordRule(itemValue, data.username)
                if (res !== '校验通过') {
                  return new Error(res)
                }
              },
            },
          ],
          nickname: [
            { required: true, message: '请输入用户昵称', trigger: 'blur' },
          ],
          posts: [
            {
              validator({ itemValue, data }) {
                // 自定义校验
                if (data.postIds.length == 0) {
                  return new Error('选择选择岗位')
                }
              },
            },
          ],
          status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        },
        rulesRoleTable: {
          dataScope: [
            { required: true, message: '请选择数据权限', trigger: 'blur' },
          ],
          dataScopeDeptIds: [
            {
              validator({ cellValue, rule, rules, row, columnIndex }) {
                // 自定义校验
                if (row.dataScope == 2 && row.dataScopeDeptIds.length == 0) {
                  return new Error('请选择数据范围')
                }
              },
            },
          ],
        },
        roleTableColumn: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 50 },
          {
            field: 'name',
            title: '角色',
            showOverflow: true,
            width: 320,
            type: 'html',
          },
          {
            field: 'dataScope',
            title: '数据范围',
            showOverflow: true,
            width: 260,
            editRender: {
              enabled: true,
              autofocus: '.el-input__inner',
            },
            slots: {
              default: 'selectRoleDataPermission',
              edit: 'updateSelectRole',
            },
          },
          {
            field: 'dataScopeDeptIds',
            title: '数据权限',
            showOverflow: true,
            width: 320,
            editRender: {
              enabled: true,
              autofocus: '.el-input__inner',
            },
            slots: {
              default: 'deptName',
              edit: 'selectDept',
            },
          },
          {
            field: 'remark',
            title: '备注',
            showOverflow: true,
            width: 300,
          },
        ],
        title: '',
        dialogFormVisible: false,
        sexList: [],
        statusList: [
          { key: 0, display_name: '启用' },
          { key: 1, display_name: '停用' },
        ],
        deptTree: [],
        posts: [],
        dataScope: [],
        listLoading: false,
        subLoading: false,
      })

      const showEdit = (row) => {
        state.listLoading = true
        if (!row.id) {
          state.title = translate('添加')
          getOpt()
            .then((res) => {
              if (res.code === 0 || res.code === 200) {
                const { data } = res
                state.sexList = data.sex
                state.posts = data.post
                state.dataScope = data.dataScope.map((item) => {
                  item.value = $XEUtils.toNumber(item.value)
                  return item
                })
                state.deptTree = $XEUtils.toArrayTree(
                  $baseLodash.cloneDeep(data.dept),
                  {
                    key: 'id',
                    parentKey: 'parentId',
                  }
                )
              }
              state.listLoading = false
            })
            .catch((err) => {
              state.listLoading = false
            })
        } else {
          state.title = translate('编辑')
          getUserById(row.id)
            .then((response) => {
              if (response.code === 0 || response.code === 200) {
                const { data } = response
                state.form = data.userInfo
                state.dataScope = data.dataScope.map((item) => {
                  item.value = $XEUtils.toNumber(item.value)
                  return item
                })
                state.sexList = data.sex
                state.posts = data.post
                if (data.dataScope) {
                  state['roleGrid'].loadData(data.userRole)
                }
                state.deptTree = $XEUtils.toArrayTree(
                  $baseLodash.cloneDeep(data.dept),
                  {
                    key: 'id',
                    parentKey: 'parentId',
                  }
                )
              }
              state.listLoading = false
            })
            .catch((err) => {
              state.listLoading = false
            })
        }
        state.dialogFormVisible = true
      }

      const save = async () => {
        const validate = await state['formRef']
          .validate()
          .catch((validate) => validate)
        const errMap = await state['roleGrid'].validate(true)
        if (!validate && !errMap) {
          const { tableData } = state['roleGrid'].getTableData()
          if (tableData.length < 1) {
            $baseMessage(
              translate(`请在用户角色中增加角色”！`),
              'error',
              'vab-hey-message-success'
            )
            return
          }
          state.subLoading = true
          state.form.userRoleDOList = tableData
          state.form.password = state.form.pwd
          const { code, data, msg } = await saveOrUpdateUser(state.form).catch(
            (err) => {
              state.subLoading = false
            }
          )
          state.subLoading = false
          if (code === 0 || code === 200) {
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data', data)
            close()
          } else {
            $baseMessage(msg, 'error', 'vab-hey-message-success')
          }
        }
      }

      const addUserRole = () => {
        state.roleListRef.showOpen()
      }

      const delUserRole = () => {
        state['roleGrid'].removeCheckboxRow()
      }

      const selectRoleDataPermission = (val) => {
        const data = state.dataScope.find((item) => {
          return item.value === val.dataScope
        })
        if (data) {
          return data.label
        } else {
          return ''
        }
      }

      const selectDeptName = (val) => {
        const name = []
        $XEUtils.eachTree(state.deptTree, (item) => {
          if ($XEUtils.includes(val.dataScopeDeptIds, item.id)) {
            name.push(item.name)
          }
        })
        return name.join(',')
      }

      const fetchData = (val) => {
        const { tableData } = state['roleGrid'].getTableData()
        val.forEach((item) => {
          //管理员数据权限范围
          item.qdataScope = item.dataScope
          item.dataScope = ''
          item.dataScopeDeptIds = []
        })
        const data = $baseLodash.unionBy(tableData, val, 'roleId')

        state['roleGrid'].loadData($baseLodash.cloneDeep(data))
      }

      const close = () => {
        state.form = {
          id: undefined, // 主键ID
          username: undefined, // 账号
          pwd: undefined, // 登录密码
          nickname: undefined, // 昵称
          sex: undefined, // 性别 0:男 1:女
          mobile: undefined, // 手机号码
          email: undefined, // 邮箱
          avatar: undefined, // 头像
          status: undefined, // 状态
          deptId: '', // 单位代码
          postIds: [], //岗位
          employeeId: '', //员工号
        }
        state.roleData = []
        state.dialogFormVisible = false
        state['formRef'].reset()
      }

      return {
        ...toRefs(state),
        translate,
        showEdit,
        selectRoleDataPermission,
        selectDeptName,
        close,
        save,
        addUserRole,
        delUserRole,
        fetchData,
      }
    },
  })
</script>
<style lang="scss" scoped>
  .el-tabs__new-tab {
    border: 0px !important;

    div {
      margin-right: 40px;
    }
  }
</style>
